﻿using System;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace DX
{
    class AppStart
    {

        public AppStart(ApplicationContext applicationContext, INotifyCenter notificationCenter, IHostApplicationLifetime lifetime, ILogger<AppStart> logger)
        {
            this.applicationContext = applicationContext;
            this.notificationCenter = notificationCenter;
            this._logger = logger;
            this.lifetime = lifetime;
            lifetime.ApplicationStarted.Register(OnApplicationStarted);
            lifetime.ApplicationStopping.Register(OnApplicationStopping);

        }

        private readonly ApplicationContext applicationContext;
        private readonly INotifyCenter notificationCenter;
        private readonly ILogger _logger;
        private readonly IHostApplicationLifetime lifetime;

        private void OnApplicationStopping()
        {

            notificationCenter.Close();
            Application.ExitThread();
            Application.Exit();


        }

        private void OnApplicationStarted()
        {
            _logger.LogInformation("Application Started");
            _logger.LogInformation("UI:[{MainForm}] Opening....", applicationContext.MainForm);
            RunApp();
        }

        private void RunApp()
        {
            try
            {                
                notificationCenter.Create();
                notificationCenter.Add("退出", OnApplicationStopping);
                applicationContext.MainForm.StartPosition = FormStartPosition.CenterScreen;
                applicationContext.MainForm.ShowInTaskbar = true;
                Application.Run(applicationContext);
                _logger.LogInformation($"UI closeing");
                OnApplicationStopping();
                lifetime.StopApplication();
            }
            catch (Exception e)
            {
                _logger.LogError(e, "RunApp error,{MainForm}", applicationContext.MainForm);
                throw;
            }
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {





            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {

            return Task.CompletedTask;
        }
    }
}
